package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
- 酒店搜索和分页
- 酒店结果过滤
- 我周边的酒店
- 酒店竞价排名
 */
@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {

        try {
            // 1获取SearchRequest对象
            SearchRequest request = new SearchRequest("hotel");

            // 2添加 DSL 查询条件
            // 2.1 条件过滤
            buildQuery(requestParams, request);
            // 2.2 分页查询
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);
            // 2.3 排序查询
            sortQuery(requestParams, request);
            // 2.4 高亮显示
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            // 3发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            // 4解析响应
            return parseResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索失败~~~");   // 相当于return
        }
    }

    /*DSL排序*/
    public void sortQuery(RequestParams requestParams, SearchRequest request) {
        // 距离升序distance
        String location = requestParams.getLocation();
        if (StringUtils.isNotBlank(location)) {
            request.source().sort(
                    SortBuilders
                            .geoDistanceSort("location", new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }

        String sortBy = requestParams.getSortBy();
        // 评价降序 score
        if ("score".equals(sortBy) && StringUtils.isNotBlank(sortBy)) {
            request.source().sort("score", SortOrder.DESC);
        }
        // 价格升序 price
        if ("price".equals(sortBy) && StringUtils.isNotBlank(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        }
    }

    /*添加DSL语句*/
    /*尔查询是用must、must_not、should、filter等方式组合查询
        must：必须匹配的条件，可以理解为“与”
        should：选择性匹配的条件，可以理解为“或”
        must_not：必须不匹配的条件，不参与打分
        filter：必须匹配的条件，不参与打分
    * */
    public void buildQuery(RequestParams requestParams, SearchRequest request) {
        // 1.准备Boolean查询  BoolQueryBuilder参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1.关键字搜索，match查询，放到must中
        String key = requestParams.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 不为空，根据关键字查询
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            // 为空，查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //1.2 brand
        String brand = requestParams.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand)); // 过滤 精准查询
        }
        //1.3 city
        String city = requestParams.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city)); // 过滤 精准查询
        }
        //1.4 startName
        String starName = requestParams.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName)); // 过滤 精准查询
        }
        //1.5 price range
        Integer maxPrice = requestParams.getMaxPrice();
        Integer minPrice = requestParams.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        //算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery, // 原始查询，boolQuery
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ // function数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), // 过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(10) // 算分函数
                        )
                }
        );

        //封装查询条件  QueryBuilder接口的实现类 query 查询条件要放入request对象中
        //request.source().query(boolQuery);
        request.source().query(functionScoreQuery);
    }

    /*解析响应*/
    public PageResult parseResponse(SearchResponse response) {
        // 4. 解析响应
        SearchHits searchHits = response.getHits();
        // 4.1 获取总条数
        TotalHits totalHits = searchHits.getTotalHits();
        long total = totalHits.value;
        System.out.println("total = " + total);

        // 4.2 获取文档数组
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> list = new ArrayList<>(hits.length); // 提前指定初始化长度 优化扩容时间

        // 4.3 遍历获取
        for (SearchHit hit : hits) {
            // 获取 _source
            String sourceJson = hit.getSourceAsString();
            // 解析json
            HotelDoc hotelDoc = JSON.parseObject(sourceJson, HotelDoc.class);
            // 获取高亮
            Map<String, HighlightField> map = hit.getHighlightFields();
            // 如果不为空 覆盖非高亮 封装到hotelDoc
            if (map != null && !map.isEmpty()) {
                // 2）根据字段名，获取高亮结果
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    // 3）获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4）把高亮结果放到HotelDoc中
                    hotelDoc.setName(hName);
                }
            }

            // 获取 排序信息
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                // 数组第一个是  地理位置的距离排序
                hotelDoc.setDistance(sortValues[0]);
            }
            // 前端需要的信息 添加到集合
            list.add(hotelDoc);
        }
        System.out.println("list = " + list);
        return new PageResult(total, list);
    }

    /*过滤查询*/
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.request
            SearchRequest request = new SearchRequest("hotel");
            // 2.DSL
            // 2.1query
            buildQuery(params, request);
            // 2.2设置query size
            request.source().size(0);
            // 2.3聚合查询
            aggregationQuery(request);
            // 3.发出请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4. 解析聚合过滤结果
            Map<String, List<String>> aggsResultMap = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggsByName(aggregations, "brandAgg");
            aggsResultMap.put("brand", brandList);
            List<String> cityList = getAggsByName(aggregations, "cityAgg");
            aggsResultMap.put("city", cityList);
            List<String> starList = getAggsByName(aggregations, "starAgg");
            aggsResultMap.put("starName", starList);
            return aggsResultMap;
        } catch (IOException e) {
            throw new RuntimeException("过滤查询失败~~~", e);
        }
    }

    /*获取聚合后的key*/
    public List<String> getAggsByName(Aggregations aggregations, String aggName) {
        // 4.1 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 获取 buckets{"key":"如家","doc_count":2}
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString(); // "key":"如家" "key":"汉庭"
            list.add(key);
        }
        return list;
    }

    /*添加聚合参数*/
    public void aggregationQuery(SearchRequest request) {
        // Bucket（桶）：对文档数据分组，并统计每组数量
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")   // 聚合的类型，按照品牌值聚合，所以选择term
                .field("brand")            // 品牌分桶
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100));
    }

    /*拼音分词 自动补全*/
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            // request
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(
                    new SuggestBuilder().addSuggestion(
                            "hotelSuggest",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(prefix)
                                    .skipDuplicates(true)
                                    .size(10)
                    )
            );
            // 发起请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 解析结果
            Suggest suggest = response.getSuggest();
            //System.out.println("suggest = " + suggest.toString());
            // 根据补全查询名称，获取补全结果
            // Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>
            CompletionSuggestion suggestions = suggest.getSuggestion("hotelSuggest");
            // 获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            System.out.println("options = " + options);
            // 遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException("自动补全失败~~~", e);
        }
    }


    @Override
    public void saveById(Long hotelId) {
        try {
            // 从数据库查询
            Hotel hotel = getById(hotelId);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            String jsonString = JSON.toJSONString(hotelDoc);

            // 在插入 or 更新
            IndexRequest request = new IndexRequest("hotel").id(hotelId.toString());
            request.source(jsonString, XContentType.JSON);
            // 发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("新增或修改酒店数据失败", e);
        }
    }

    @Override
    public void deleteById(Long hotelId) {
        try {
            DeleteRequest request = new DeleteRequest("hotel", hotelId.toString());
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("删除酒店数据失败", e);
        }
    }
}





